<template>
  <div class="inventory-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>库存管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">添加库存</el-button>
        <el-button type="warning" @click="getLowStockItems">库存预警</el-button>
        <el-button type="success" @click="refreshInventory">刷新</el-button>
      </div>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-item">
        <label>产品ID</label>
        <el-input v-model="searchForm.productId" placeholder="请输入产品ID" clearable></el-input>
      </div>
      <div class="search-item">
        <label>仓库ID</label>
        <el-input v-model="searchForm.warehouseId" placeholder="请输入仓库ID" clearable></el-input>
      </div>
      <div class="search-item switch">
        <span class="label">所有库存</span>
        <el-switch v-model="searchForm.lowStock"></el-switch>
        <span class="label">库存预警</span>
      </div>
      <div class="search-buttons">
        <el-button type="primary" @click="searchInventory">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="inventoryList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column prop="productId" label="产品ID" width="150"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="150">
          <template #default="scope">
            {{ productNames[scope.row.productId] || '加载中...' }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="总数量" width="90"></el-table-column>
        <el-table-column prop="availableQuantity" label="可用数量" width="90">
          <template #default="scope">
            <span :class="{ 'low-stock': isLowStock(scope.row) }">
              {{ scope.row.availableQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseId" label="仓库ID" width="100"></el-table-column>
        <el-table-column prop="location" label="库位" width="100"></el-table-column>
        <el-table-column label="操作" width="340">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openStockDialog('add', scope.row)">入库</el-button>
            <el-button type="warning" size="small" @click="openStockDialog('reduce', scope.row)" 
              :disabled="scope.row.availableQuantity <= 0">出库</el-button>
            <el-button type="info" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页区域 -->
    <div class="pagination-area">
      <span class="total-info">共 {{ total }} 条</span>
      <div class="page-control">
        <span>{{ currentPage }}/{{ Math.ceil(total/pageSize) }}</span>
        <el-button-group>
          <el-button size="small" @click="handleCurrentChange(currentPage-1)" :disabled="currentPage <= 1">
            上一页
          </el-button>
          <el-button size="small" @click="handleCurrentChange(currentPage+1)" :disabled="currentPage >= Math.ceil(total/pageSize)">
            下一页
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 对话框部分保持不变 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑库存' : '添加库存'"
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model="form.productId" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="总数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0" />
        </el-form-item>
        <el-form-item label="预留数量" prop="reservedQuantity">
          <el-input-number v-model="form.reservedQuantity" :min="0" :max="form.quantity" />
        </el-form-item>
        <el-form-item label="安全库存" prop="safetyStock">
          <el-input-number v-model="form.safetyStock" :min="0" />
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-input v-model="form.warehouseId" />
        </el-form-item>
        <el-form-item label="库位" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="form.batchNumber" />
        </el-form-item>
        <el-form-item label="有效期" prop="expiryDate">
          <el-date-picker 
            v-model="form.expiryDate" 
            type="date" 
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="stockDialogVisible"
      :title="stockDialogTitle"
      width="400px"
    >
      <el-form ref="stockFormRef" :model="stockForm" label-width="100px">
        <el-form-item label="产品ID">
          <span>{{ stockForm.productId }}</span>
        </el-form-item>
        <el-form-item label="当前可用库存">
          <span>{{ stockForm.currentStock }}</span>
        </el-form-item>
        <el-form-item label="操作数量" prop="quantity">
          <el-input-number 
            v-model="stockForm.quantity" 
            :min="1" 
            :max="stockDialogType === 'reduce' ? stockForm.currentStock : undefined"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStockChange">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import inventoryApi, { IInventoryDto, IInventoryRequest } from '../../api/inventory';
import productApi from '../../api/product';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Warning, Refresh } from '@element-plus/icons-vue';
import { formatDate as formatDateUtil } from '../../utils/date';

// 库存列表
const inventoryList = ref<IInventoryDto[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const productNames = ref<Record<string, string>>({});

// 搜索表单
const searchForm = reactive({
  productId: '',
  warehouseId: '',
  lowStock: false
});

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentId = ref<number | null>(null);

// 添加/编辑表单
const form = reactive<IInventoryRequest>({
  productId: '',
  quantity: 0,
  reservedQuantity: 0,
  safetyStock: 0,
  warehouseId: 'WH001', // 默认仓库
  location: '',
  batchNumber: '',
  expiryDate: ''
});

const rules = {
  productId: [{ required: true, message: '请输入产品ID', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  safetyStock: [{ required: true, message: '请输入安全库存', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请输入仓库ID', trigger: 'blur' }]
};

// 出入库对话框
const stockDialogVisible = ref(false);
const stockDialogType = ref<'add' | 'reduce'>('add');
const stockDialogTitle = computed(() => 
  stockDialogType.value === 'add' ? '入库操作' : '出库操作'
);
const stockForm = reactive({
  id: 0,
  productId: '',
  currentStock: 0,
  quantity: 1
});

// 初始化
onMounted(() => {
  getInventoryList();
});

// 获取库存列表
const getInventoryList = async () => {
  loading.value = true;
  try {
    const res = await inventoryApi.getAllInventories();
    if (res && res.code === 200 && res.data) {
      inventoryList.value = res.data;
      total.value = res.data.length;
      getProductNames();
    }
  } catch (error) {
    console.error('获取库存列表失败:', error);
    ElMessage.error('获取库存列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取库存不足的商品
const getLowStockItems = async () => {
  loading.value = true;
  try {
    const res = await inventoryApi.getLowStockItems();
    if (res && res.code === 200 && res.data) {
      inventoryList.value = res.data;
      total.value = res.data.length;
      getProductNames();
      ElMessage.warning(`发现 ${res.data.length} 个库存不足的商品`);
    }
  } catch (error) {
    console.error('获取库存不足商品失败:', error);
    ElMessage.error('获取库存不足商品失败');
  } finally {
    loading.value = false;
  }
};

// 获取产品名称
const getProductNames = async () => {
  const productIds = inventoryList.value
    .map(item => item.productId)
    .filter((id, index, self) => self.indexOf(id) === index); // 去重
    
  for (const productId of productIds) {
    if (!productNames.value[productId]) {
      try {
        const res = await productApi.getProductById(productId);
        if (res && res.code === 200 && res.data) {
          productNames.value[productId] = res.data.name;
        }
      } catch (error) {
        console.error(`获取产品 ${productId} 信息失败:`, error);
        productNames.value[productId] = '未知产品';
      }
    }
  }
};

// 判断是否库存不足
const isLowStock = (row: IInventoryDto): boolean => {
  return row.availableQuantity <= row.safetyStock;
};

// 格式化日期
const formatDate = (dateStr?: string): string => {
  if (!dateStr) return '未设置';
  return formatDateUtil(dateStr);
};

// 刷新库存
const refreshInventory = () => {
  currentPage.value = 1;
  getInventoryList();
};

// 搜索库存
const searchInventory = async () => {
  loading.value = true;
  try {
    if (searchForm.lowStock) {
      await getLowStockItems();
    } else if (searchForm.productId) {
      const res = await inventoryApi.getProductInventory(searchForm.productId);
      if (res && res.code === 200 && res.data) {
        inventoryList.value = [res.data];
        total.value = 1;
        getProductNames();
      }
    } else if (searchForm.warehouseId) {
      const res = await inventoryApi.getWarehouseInventories(searchForm.warehouseId);
      if (res && res.code === 200 && res.data) {
        inventoryList.value = res.data;
        total.value = res.data.length;
        getProductNames();
      }
    } else {
      await getInventoryList();
    }
  } catch (error) {
    console.error('搜索库存失败:', error);
    ElMessage.error('搜索库存失败');
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.productId = '';
  searchForm.warehouseId = '';
  searchForm.lowStock = false;
  refreshInventory();
};

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row: IInventoryDto) => {
  isEdit.value = true;
  currentId.value = row.id || null;
  Object.assign(form, {
    productId: row.productId,
    quantity: row.quantity,
    reservedQuantity: row.reservedQuantity,
    safetyStock: row.safetyStock,
    warehouseId: row.warehouseId,
    location: row.location,
    batchNumber: row.batchNumber,
    expiryDate: row.expiryDate
  });
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    productId: '',
    quantity: 0,
    reservedQuantity: 0,
    safetyStock: 0,
    warehouseId: 'WH001',
    location: '',
    batchNumber: '',
    expiryDate: ''
  });
  currentId.value = null;
};

// 提交表单
const submitForm = async () => {
  try {
    if (isEdit.value && currentId.value) {
      const res = await inventoryApi.updateInventory(currentId.value, form);
      if (res && res.code === 200) {
        ElMessage.success('更新库存成功');
        dialogVisible.value = false;
        refreshInventory();
      }
    } else {
      const res = await inventoryApi.createInventory(form);
      if (res && res.code === 200) {
        ElMessage.success('添加库存成功');
        dialogVisible.value = false;
        refreshInventory();
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 确认删除
const confirmDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该库存记录吗？此操作不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await inventoryApi.deleteInventory(id);
      if (res && res.code === 200) {
        ElMessage.success('删除成功');
        refreshInventory();
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 用户取消删除，不做任何操作
  });
};

// 打开出入库对话框
const openStockDialog = (type: 'add' | 'reduce', row: IInventoryDto) => {
  stockDialogType.value = type;
  stockForm.id = row.id || 0;
  stockForm.productId = row.productId;
  stockForm.currentStock = row.availableQuantity;
  stockForm.quantity = 1;
  stockDialogVisible.value = true;
};

// 提交出入库操作
const submitStockChange = async () => {
  try {
    if (stockDialogType.value === 'add') {
      const res = await inventoryApi.addStock(stockForm.productId, stockForm.quantity);
      if (res && res.code === 200) {
        ElMessage.success(`成功入库 ${stockForm.quantity} 件商品`);
        stockDialogVisible.value = false;
        refreshInventory();
      }
    } else {
      const res = await inventoryApi.reduceStock(stockForm.productId, stockForm.quantity);
      if (res && res.code === 200) {
        ElMessage.success(`成功出库 ${stockForm.quantity} 件商品`);
        stockDialogVisible.value = false;
        refreshInventory();
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  // 这里可以根据需要实现分页逻辑
};
</script>

<style scoped>
.inventory-page {
  background-color: #f5f7fa;
  min-height: 100%;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 15px 20px;
  margin-bottom: 15px;
}

.page-header h2 {
  font-size: 18px;
  font-weight: normal;
  margin: 0;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-area {
  background-color: white;
  padding: 15px 20px;
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #606266;
  font-size: 14px;
}

.search-item.switch {
  display: flex;
  align-items: center;
}

.search-buttons {
  margin-left: auto;
}

.table-section {
  background-color: white;
  padding: 15px 20px;
  margin-bottom: 15px;
}

.pagination-area {
  background-color: white;
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.page-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-control span {
  color: #606266;
  font-size: 14px;
}

.low-stock {
  color: #F56C6C;
  font-weight: bold;
}
</style> 